/*
* Copyright (c) 2021,西安研奇网络科技有限公司
* All rights reserved.
*
* 文件名称：main.c
* 创建日期：2020/12/19
* 摘 要：调试日志接口实现
*
* 当前版本：1.0
* 作 者：赵满刚
* 完成日期：
*/
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include "write_log.h"

#define TIME_STR_LEN 128

int proxy_logfd = -1;                               /** 日志文件描述符 */
static debug_level_em debug_level = LOG_WARNING;  /** 日志文件级别，默认warning */

static const char *error_strs[LOG_MAX] = {
    "[Error]",
    "[Warning]",
    "[Info]",
    "[Debug]"
};


static char *get_cur_time(time_t t)
{
	static char	time[TIME_STR_LEN] = {0};
	char	*point = NULL;
	struct tm	*tmp = NULL;

	tmp = localtime(&t);
	strftime(time, 127, "%Y/%m/%d %T", tmp);
	for (point = time; *point; point++) {
		if (*point == '/') {
			*point = '-';
		}
	}
	return time;
}


void debug_level_set(debug_level_em level)
{
    debug_level = level;
}

void debug_file_set(char* path)
{
    if (NULL == path)
    {
        return;
    }

    char file_name[MAX_LOG_PATH] = {0};
    time_t timep;
    time (&timep);
    snprintf(file_name  , MAX_LOG_PATH, "%slog%s", path, get_cur_time(timep));
    proxy_logfd = open(file_name, O_WRONLY | O_CREAT); 
}


void debug_file_close()
{
    close(proxy_logfd);
    proxy_logfd = -1;
}


void debug_output(debug_level_em type, const char *file, int lineno, const char *fmt, ...)
{
    if (type > debug_level)
        return;

    if (!fmt)
        return;

    if (!file)
        file = "no_src.c";

    time_t timep;
    time (&timep);
    char msg[MAX_DEBUG_MSG_SIZE] = {0};
    snprintf(msg, MAX_DEBUG_MSG_SIZE, "[%s]%8s[%15s:%5d][%d]>>>> ", get_cur_time(timep), error_strs[type], file, lineno, getpid());
    int idx = strlen(msg);

    va_list ap;
    va_start(ap, fmt);
    vsnprintf(&msg[idx], MAX_DEBUG_MSG_SIZE - idx, fmt, ap);
    va_end(ap);

    if (proxy_logfd != -1) {
        /** TODO:写入调试文件，控制文件大小 */
        write(proxy_logfd, msg, strlen(msg));
    } else {
        printf("%s\n", msg);
    }
    return ;
}

